import {action, observable, runInAction} from "mobx";
import {BaseResInterface, sendGetRequest} from "../../../net";
import {ProductCategoryRelation, ProductModelInterface} from "../../../net/instance/CommenModelInstance";
import {realm} from "../../../dao";
import * as _ from "lodash";
import {defaultArr, defaultObj, isSameDate} from "../../../util";
import Collection = Realm.Collection;
import {BannerStore} from "./banner";

interface BoutiquesResInterface extends BaseResInterface {
    data: ProductModelInterface[]
}


export class BoutiquesStore {
    @observable
    boutiquesProducts: ProductModelInterface[] = [];

    dbProductStore: Collection<ProductModelInterface> = defaultArr;
    dbProductCategoryRelationStore: Collection<ProductCategoryRelation> = defaultArr;

    constructor() {
        this.dbProductStore = realm.objects<ProductModelInterface>("Product");
        this.dbProductCategoryRelationStore = realm.objects<ProductCategoryRelation>("ProductCategoryRelation");
    }

    initialListValue(categoryId: number) {
        const productCategoryRelations = this.dbProductCategoryRelationStore.filtered(`categoryId = ${categoryId}`);
        const productIds = productCategoryRelations.map(relation => relation.productId);
        //如果本地没有改分类的商品测直接取消初始化
        if (!productIds.length) return;

        const queryStr = productIds.reduce((initVal, id, index) => {
            const isLast = index == productIds.length - 1;
            return initVal + (isLast ? `${id} ` : `${id} OR id = `);
        }, "id = ");
        const specialProducts = this.dbProductStore.filtered("special = 1 ");
        if (specialProducts.length) {
            this.boutiquesProducts = _.toArray(specialProducts.filtered(queryStr).sorted("id"));
        }
    }

    @action.bound
    async getBoutiques(categoryId: number) {
            this.initialListValue(categoryId);
        const {data} = await sendGetRequest<BoutiquesResInterface>("main/getBoutiquesProduct", {categoryId});
        runInAction(() => {
            this.boutiquesProducts = data;
        });
    }

}

export function getBoutiquesStoreInstance() {
    return new BoutiquesStore();
}

const BoutiquesStoreInstance = getBoutiquesStoreInstance();
export default BoutiquesStoreInstance